<?php

session_start();

/*
 * Created on 18 d�c. 2005
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
include_once('Language.php');
include_once('IniFile.php');
include_once('Format.php');

$Configuration;
$TypeAds = 1;
$ColsNumber = 1;

function printHeader($title, $titleH2='', $activetab='')
{
	printHeaderContent($title, $titleH2, $activetab);

	print "<div id=\"content\">";
	print "<h2>". $titleH2 ."</h2>";
}

function printNoBorderHeader($title, $titleH2='', $activetab='')
{
	printHeaderContent($title, $titleH2, $activetab);

	print "<div id=\"noBorderContent\">";
	print "<h2>". $titleH2 ."</h2>";
}

function printHeaderContent($title, $titleH2='', $activetab='')
{
	global $Navigation;
	global $TypeAds;
	global $ColsNumber;
	
	if ( empty($titleH2) )

		$titleH2 = $title;
	
	header("Content-type:text/html;charset=utf-8");
	
	print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
	print "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"" . getCurrentLanguage() . "\" xml:lang=\"" . getCurrentLanguage() . "\"><head>";
	
	if ( ! empty($title) )
		print "<title>$title</title>";
	
	print "<meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\" />";
	print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Styles/Default/master.css\" />";
	print '<link rel="icon" type="image/png" href="/favicon.png">';
	if ($activetab == 'browse')	 {
		print '<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />';
		print '<!--[if lte IE 8]>';
		print '<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />';
		print '<![endif]-->';
	}

	if ( $ColsNumber==2 )
		print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Styles/Default/twocols.css\" />";
	
	print "<!--[if lte IE 6]>";
    print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Styles/Default/IE.css\" />";
	print "<![endif]-->";
	print "</head><body>";
	include_once("_google_tag.php");
	print "<div id=\"container\">";
	print "<div id=\"header\">";
	print "<h1><a href=\"". formatUrl('/') ."\">". getTerm('base', 'site_name') ."</a></h1>";
	print "<p>". getTerm('base', 'site_slogan') ."</p>";
	print "</div>";
	
	print "<div id=\"menu\">";
	print "<h2>" . getTerm('menu','navigation') . "</h2><ul>";
	print "<li><a href=\"". formatUrl('/') ."\"". ($activetab=='home' ? ' class="active"' : '') .">" . getTerm('menu', 'home') . "</a></li>";
	print "<li><a href=\"". formatUrl('/parceling/receive') ."\"". ($activetab=='parceling' ? ' class="active"' : '') .">" . getTerm('menu', 'parceling') . "</a></li>";
	print "<li><a href=\"". formatUrl('/search/') ."\"". ($activetab=='search' ? ' class="active"' : '') .">" . getTerm('menu', 'search') . "</a></li>";
	//if ( $activetab=='albums' )
	print "<li><a href=\"". formatUrl('/albums/') ."\"". ($activetab=='albums' ? ' class="active"' : '') .">" . getTerm('menu', 'albums') . "</a></li>";
	print "<li><a href=\"". formatUrl('/messaging/') ."\"". ($activetab=='messaging' ? ' class="active"' : '') .">" . getTerm('menu', 'messaging') . "</a></li>";
	
	//if ( $activetab=='browse' )
		print "<li><a href=\"". formatUrl('/browse/') ."\"". ($activetab=='browse' ? ' class="active"' : '') .">" . getTerm('menu', 'browse') . "</a></li>";
		
	//print "<li><a href=\"". formatUrl('/') ."\"". ($activetab=='home' ? ' class="active"' : '') .">" . getTerm('menu', 'lost') . "</a></li>";
	print "<li><a href=\"". formatUrl('/friends/') ."\"". ($activetab=='friends' ? ' class="active"' : '') .">" . getTerm('menu', 'friends') . "</a></li>";
	print "<li><a href=\"". formatUrl('/account/') ."\"". ($activetab=='account' ? ' class="active"' : '') .">" . getTerm('menu', 'account') . "</a></li>";
	print "</ul></div>";
	
	print "<div id=\"navigation\"><p>";
	if ( ! empty($Navigation) )
	{
		print "<a href=\"". formatUrl('/') ."\">Penpal Hub</a>";
	
		for ( $i=0 ; $i<count($Navigation) ; $i++ )

			if ( $i==count($Navigation)-1 )
				print " &gt; <strong>". $Navigation[$i]['title'] ."</strong>";

			else
				print " &gt; <a href=\"". $Navigation[$i]['url'] ."\">". $Navigation[$i]['title'] ."</a>";
	}
	else
		print getTerm('base', 'site_root');

	print "</p></div>";
}

function modifyProfile($user, $country, $photo, $city, $gender, $description, $birthday)
{
	query("	INSERT INTO profile
			(user,country,photo,city,gender,description,birthday,creation,valid,current)
			VALUES
			('$user', '$country', '$photo', '$city', '$gender', '$description', '$birthday', NOW(), NULL, 0 );");
	
	//print "test test";
	
	logEvent(5);
}

function getLatestProfile($user)
{
	$rh = query("	SELECT p.id,u.username,u.email,u.banned,u.status,p.country,p.continent,p.photo,p.city,p.gender,p.description,p.birthday,ph.type,p.status
					FROM user u
					LEFT JOIN profile p ON p.user=u.id
					LEFT JOIN photo ph ON ph.id=p.photo
					WHERE u.id='$user'
					ORDER BY p.creation DESC
					LIMIT 1;");
	
	if ( mysql_num_rows($rh)==0 )
		return -1;
		
	return mysql_fetch_assoc($rh);
}

function getCurrentProfile($user)
{
	$rh = query("	SELECT u.id,u.username,u.email,u.valid,u.banned,u.status,p.country,p.photo,p.city,p.gender,p.description,p.birthday,p.status,p.continent
					FROM user u
					LEFT JOIN profile p ON p.user=u.id AND p.current=1
					WHERE u.id='". $_SESSION['user'] ."';");
	
	if ( mysql_num_rows($rh)==0 )
		return -1;
		
	return mysql_fetch_assoc($rh);
}

function printExtra()
{
	print "</div>";
	print "<div id=\"extra-content\">";
}

function hasValidProfile($user)
{
	$rh = query("SELECT * FROM profile WHERE user=$user AND valid IS NOT NULL;");
	
	return mysql_num_rows($rh)>0;
}

function isBanned($user)
{
	$rh = query("SELECT banned FROM user WHERE id=$user;");

	if ( mysql_num_rows($rh)==0 )
		return false;
	
	list($banFlag) = mysql_fetch_array($rh);
	return $banFlag==1;
}

function processUserMessages($userid)
{
	$sql = "SELECT m.*,u.username AS 'sendername',t.username AS 'tousername',t.email
			FROM user u
			JOIN message m ON m.from=u.id
			JOIN user t ON m.to=t.id
			WHERE u.id=$userid
			AND draftflag=0
			AND processed=0;";
	
	$rh = query($sql);
	
	while ( $msg = mysql_fetch_assoc($rh) )
	{
		$subject = $msg['subject'];
		$sendername = $msg['sendername'];
		$tousername = $msg['tousername'];
		
		query("	INSERT INTO message
						(`from`,`to`,`toname`,`date`,`subject`,`message`,`draftflag`,`visibleby`,`processed`)
				VALUES	('${msg[from]}', '${msg[to]}', '${msg[toname]}', '${msg[date]}', '${msg[subject]}', '${msg[message]}',0,'${msg[to]}',1) ;");
		
		$messageId = mysql_insert_id();
		
		$messageUrl = 'http://'. $_SERVER["SERVER_NAME"] .'/messaging/message-'. $messageId .'.html';
		
		$parameters = array($sendername, $tousername, $subject, $messageUrl);
		
		sendMail('message', $msg['email'], $tousername, $parameters);
		
		$_SESSION['message'] = fill( getTerm('messaging', 'message_sent') , $tousername);
		
		logEvent(3, "to=$username");
		
		query("UPDATE message SET processed=1 WHERE id=${msg[id]};");
	}
}
function processUserParcels($userid)
{
	$sql = "SELECT m.*,u.username AS 'sendername',t.username AS 'tousername',t.email
			FROM user u
			JOIN parcel m ON m.from=u.id
			JOIN user t ON m.to=t.id
			WHERE u.id=$userid
			AND draftflag=0
			AND processed=0;";
	
	$rh = query($sql);
	
	while ( $msg = mysql_fetch_assoc($rh) )
	{
		$subject = $msg['subject'];
		$sendername = $msg['sendername'];
		$tousername = $msg['tousername'];
		
		query("	INSERT INTO parcel
						(`from`,`to`,`toname`,`date`,`subject`,`parcel`,`draftflag`,`visibleby`,`processed`)
				VALUES	('${msg[from]}', '${msg[to]}', '${msg[toname]}', '${msg[date]}', '${msg[subject]}', '${msg[parcel]}',0,'${msg[to]}',1) ;");
		
		$parcelId = mysql_insert_id();
		
		$parcelUrl = 'http://'. $_SERVER["SERVER_NAME"] .'/parceling/parcel-'. $parcelId .'.html';
		
		$parameters = array($sendername, $tousername, $subject, $parcelUrl);
		
		sendMail('parcel', $msg['email'], $tousername, $parameters);
		
		$_SESSION['parcel'] = fill( getTerm('parceling', 'parcel_sent') , $tousername);
		
		logEvent(3, "to=$username");
		
		query("UPDATE parcel SET processed=1 WHERE id=${msg[id]};");
	}
}
function logEvent($typeId,$comments='',$userId=0)
{
	if ( ! empty($_SESSION['user']) )
		$userId = $_SESSION['user'];
	
	if ( ! empty($userId) )
	{
		if ( empty($_SESSION['hostname']) )
			$_SESSION['hostname'] = gethostbyaddr($_SERVER['REMOTE_ADDR']);
		
		$sql = "INSERT INTO event VALUES ($userId,$typeId,NOW(),'${_SERVER[REMOTE_ADDR]}','${_SESSION[hostname]}','$comments');";
		
		query($sql);
	}
}

function printQuickSearch()
{
	
	print '<div class="flat-form">';
	print '<h3>'. getTerm('extra', 'quick_search') .'</h3>';
	print '<form action="/search/" method="get">';
	print '';
	
	print '<div>'. getTerm('extra', 'country') .'</div>';
	$rh = query('SELECT id,name FROM region WHERE is_country=1 ORDER BY name;');
	
	$countries = array();
	while ( $country = mysql_fetch_array($rh) )
	{
		$countries[ $country[1] ] = $country[0];
	}
	
	ksort($countries);
	
	print '<div><input type="hidden" name="ac" value="search" /><select name="country" id="country"' . (isIdentified() ? '' : ' disabled="disabled"') . '><option value="">'. getTerm('search','anywhere') .'</option>';
	foreach ( $countries as $country=>$id )
		print "<option value=\"". $id ."\">". wrapString( getTerm('country', $country) , 25, '...') ."</option>";
	print '</select></div>';
	
	print '<div>'. getTerm('extra', 'age') .'</div><div>';
	
	$biasselect1 = '<select name="bias1" id="bias1"><option value="">'. getTerm('search', 'any') .'</option>';
	$biasselect2 = '<select name="bias2" id="bias2"><option value="">'. getTerm('search', 'any') .'</option>';
	for ( $i=1 ; $i<100 ; $i++ )
	{
		$biasselect1 .= "<option value=\"$i\">$i</option>";
		$biasselect2 .= "<option value=\"$i\">$i</option>";
	}
	$biasselect1 .= '</select>';
	$biasselect2 .= '</select>';
	
	print fill( getTerm('extra', 'from_to') , $biasselect1, $biasselect2 );
	
	print '</div><div>'. getTerm('extra', 'gender') .'</div><div>';
	
	print '<select name="gender" id="gender">';
	print "<option value=\"\">". getTerm('search','either') ."</option>";
	foreach ( array('female','male') as $gende )
		print "<option value=\"". $gende ."\">". getTerm('profile', $gende) ."</option>";
	print '</select>';
	
	print '</div><div><input type="submit" value="'. getTerm('extra', 'search') .'" /></div>';
	print '</form>';
	print '</div>';
}

function printFooter($full=1)
{
	print "</div>";
	
	print "<div id=\"utilities\"><p>";
	
	if ( isIdentified() )
	{
		$currentUser = getCurrentUser();
		print $currentUser['username'] ." | <a href=\"". formatUrl('/signout') ."\">". getTerm('sign_in', 'sign_out') ."</a> | ";
	}
	else
	{
		print "<a href=\"". formatUrl('/signin') ."\">". getTerm('sign_in', 'sign_in') ."</a> | ";
	}
	
	print "<a href=\"". formatUrl('/') ."\">" . getTerm('menu', 'home') . "</a> | <a href=\"". formatUrl('/about/') ."\">" . getTerm('menu', 'about') . "</a>";
		
	print "</p></div>";
	
?>

<?php
	
	print "<div id=\"footer\">";
	print "<p>&copy; ". gmdate('Y') ." <a href=\"/\">". getTerm('base', 'copyright') ."</a> | <a href=\"". formatUrl('/partners/') ."\">" . getTerm('base', 'partners') . "</a> | <a href=\"/contact/\">" . getTerm('base', 'contact') . "</a></p>";
	print "</div>";
	
	/*print '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript"><!--
_uacct = "UA-84221-3";
urchinTracker();
--></script>';*/
include_once("_google_ga.php");

	print "</div></body></html>";
}

function pushRegionNavigationItem($region)
{
	$regions = getRegionTree($region);
	$regionUrl = '';
	
	foreach ($regions as $region)
	{
		$regionUrl .= "/$region";
	
		pushNavigationItem( getTerm('country', $region), formatUrl('/browse/country'. $regionUrl .'/page-1.html') );
	}
}

function getRegionUrl($region,$page=1)
{
	$regions = getRegionTree($region);
	
	return formatUrl('/browse/country/'. implode('/', $regions) .'/page-'. $page .'.html');
}

function getRegionTree($region)
{
	$tree = array();
	
	$field = preg_match('/^[0-9]+$/i', $region) ? 'id' : 'name';
	
	$rh = query("	SELECT r1.name,r2.name,r3.name
					FROM region r1
					LEFT JOIN region r2 ON r1.parent=r2.id
					LEFT JOIN region r3 ON r2.parent=r3.id
					WHERE r1.$field='$region';");
	
	if ( mysql_num_rows($rh)>0 )
	{
		$result = mysql_fetch_array($rh);
		
		if ( $result[2] )
			array_push($tree, $result[2]);
		if ( $result[1] )
			array_push($tree, $result[1]);
		if ( $result[0] )
			array_push($tree, $result[0]);
	}
		
	return $tree;
}

function formatWords($string)
{
	//$string = preg_replace("/[^a-zA-Z0-9\\x80-\\xFF]/", '_', $string);
	$string = ereg_replace('[^a-zA-Z0-9]', '_', $string);
	$string = ereg_replace('_{2,}', '_', $string);
	$string = ereg_replace('^(_+)|(_+)$', '', $string);
	
	return $string;
}

function error404()
{
	redirect( formatUrl('/') );
}

// truncate
function wrapString($string, $length=150, $break='...')
{
	$len = strlen($string);
	
	if ( $len<=$length )
		$ret = $string;
	else
	{
		for ( $i=0 ; $i<$length ; $i++ )
	
			if ( ! isChar( ord($string[$i]) ) )
		
				$ret = substr($string, 0, $i) . $break;
				
		if ( $ret=="" )
			$ret = substr($string, 0, $length) . $break;
	}
	
	return $ret;
}

function hasPhoto($userid)
{
	$rh = query("SELECT * FROM photo WHERE user='$userid';");
	
	return mysql_num_rows($rh)>0;
}

function getUser($username)
{
	$rh = query("	SELECT u.id,u.username,u.email,u.banned,u.showfriends,u.status,p.country,p.photo,p.city,p.gender,p.description,p.birthday,ph.type,p.status,p.continent
					FROM user u
					LEFT JOIN profile p ON p.user=u.id AND p.current=1
					LEFT JOIN photo ph ON ph.id=p.photo
					WHERE u.username='$username';");
	
	if ( mysql_num_rows($rh)==0 )
		return -1;
		
	return mysql_fetch_assoc($rh);
}

function getUserById($id)
{
	$rh = query("	SELECT u.id,u.username,u.email,u.banned,u.showfriends,u.status,p.country,p.photo,p.city,p.gender,p.description,p.birthday,ph.type,p.status
					FROM user u
					LEFT JOIN profile p ON p.user=u.id AND p.current=1
					LEFT JOIN photo ph ON ph.id=p.photo
					WHERE u.id='$id';");
	
	if ( mysql_num_rows($rh)==0 )
		return -1;
		
	return mysql_fetch_assoc($rh);
}

function isFriend($userid)
{
	if ( ! isIdentified() )
		return false;
		
	$currentUser = $_SESSION['user'];
	
	$rh = query("SELECT * FROM friends WHERE user=$currentUser AND friend=$userid;");
	
	return mysql_num_rows($rh)>0;
}

function isChar($char)
{
	return ($char>=ord('a') && $char<=ord('z')) || ($char>=ord('\x7f') && $char<=ord('\xff')) ;
}

function isIdentified()
{
	return ! empty($_SESSION['user']);
}

function getCurrentUser()
{
	$rh = query("	SELECT u.id,u.username,u.email,u.banned,u.showfriends,u.status,p.country,p.photo,p.city,p.gender,p.description,p.birthday,p.status
					FROM user u
					LEFT JOIN profile p ON p.user=u.id AND p.current=1
					WHERE u.id='". $_SESSION['user'] ."';");
	
	if ( mysql_num_rows($rh)==0 )
		return -1;
		
	return mysql_fetch_assoc($rh);
}

function redirect($url)
{
	header("Status: 301 Moved Permanently");
	header("Location: $url");
	
	print($url);
	
	session_write_close();

	exit();
}

function getConfiguration($section,$parameter)
{
	global $Configuration;

	return getValue($Configuration, $section, $parameter);
}


function loginRequired($title)
{
	if ( empty($_SESSION['user']) ) {
		require('SignIn.php');
	}


}

function pushNavigationItem($title, $url)
{
	global $Navigation;
	
	array_push($Navigation, array( 'title'=>$title, 'url'=> formatUrl($url) ) );
}

function sendMail($message, $tomail, $toname, $parameters)
{
	if ( function_exists("mail") )
	{
		$eol = "\r\n";
	
		$fromname = getTerm('mail', $message ."_from");
		$subject = getTerm('mail', $message ."_subject");
		$content = '';
		
		for ( $i=0 ; $i<count($parameters) ; $i++ )
		
			$subject = str_replace('%'.($i+1), $parameters[$i], $subject);
		
		$length = getTerm('mail', $message ."_length");
		
		for ( $index=1 ; $index<=$length ; $index++ )
		{
			$line = getTerm('mail', $message ."_content_". $index);
			
			for ( $i=0 ; $i<count($parameters) ; $i++ )
			
				$line = str_replace('%'.($i+1), $parameters[$i], $line);
				
			$content = "$content$line<br/>";
		}
		
		//$headers = "Reply-to: $fromname <$from>" . $eol;
		$headers = "From: $fromname". $eol;
		$headers .= "Content-Type: text/html; charset=utf-8" .$eol;
//		echo "$tomail => $subject<br>$content<br><br>";
		mail($tomail, $subject, $content, $headers);
	}
}

function processUpload($file, $name, $type, $user, $albumId, $width, $height, $size)
{
	$path = formatWords($name);
	
	$sql = "INSERT INTO photo (user,album,type,width,height,size,name,path,creationdate) VALUES ('$user','$albumId','$type','$width','$height','$size','$name','$path',NOW());";
	
	query($sql);
	
	$photoId = mysql_insert_id();
	
	if ( $photoId>0 )
	{
		$thumbFile = createThumbnail($file, $type, 150, 150);
		$thumbdst = '../Thumbs/' .$photoId .'-small.jpg';
		copy($thumbFile, $thumbdst);
		unlink($thumbFile);
		
		$thumbFile = createThumbnail($file, $type, 250, 250);
		$thumbdst = '../Thumbs/' .$photoId .'-medium.jpg';
		copy($thumbFile, $thumbdst);
		unlink($thumbFile);
		
		$thumbFile = createSquareThumbnail($file, $type, 120);
		$thumbdst = '../Thumbs/' .$photoId .'-square.jpg';
		copy($thumbFile, $thumbdst);
		unlink($thumbFile);
		
		$filedst = '../Photos/' .$photoId .'.'. $type;
		copy($file, $filedst);
	}
	
	return $photoId;
}

function createSquareThumbnail($image, $type, $maxWidth)
{
	$outFile = "/tmp/". rand() .".thumb";
	
	if ( function_exists("imagecreatefromjpeg") )
	{
		if ( $type=='jpg' )
			$img = imagecreatefromjpeg($image);
		elseif ( $type=='png' )
			$img = imagecreatefrompng($image);
		else
			$img = imagecreatefromgif($image);
		
		if ($img)
		{
			// Get image size and scale ratio
			$width = imagesx($img);
			$height = imagesy($img);
			
			$tmp_img = imagecreatetruecolor($maxWidth, $maxWidth);
			
			if ( $width>$height )
			{
				$beginx = floor( ($width/2) - ($height/2) );
				$beginy = 0;
				$endx = $height;
				$endy = $height;
			}
			else
			{
				$beginx = 0;
				$beginy = 0;
				$endx = $width;
				$endy = $width;
			}
			
			imagecopyresized($tmp_img, $img, 0, 0, $beginx, $beginy, $maxWidth, $maxWidth, $endx, $endy);
			
			imageJpeg($tmp_img, $outFile);
			imagedestroy($tmp_img);
		}
		
		imagedestroy($img);
	}
	else
	{
		copy($image, $outFile);
	}
	
	return $outFile;
}

function createThumbnail($image, $type, $maxWidth, $maxHeight)
{
	$outFile = "/tmp/". rand() .".thumb";
	
	if ( function_exists("imagecreatefromjpeg") )
	{
		if ( $type=='jpg' )
			$img = imagecreatefromjpeg($image);
		elseif ( $type=='png' )
			$img = imagecreatefrompng($image);
		else
			$img = imagecreatefromgif($image);
		
		if ($img)
		{
			// Get image size and scale ratio
			$width = imagesx($img);
			$height = imagesy($img);
			
			$scaleW = $maxWidth / $width;
			$scaleH = $maxHeight / $height;
			$scale = $scaleW>$scaleH ? $scaleH : $scaleW;
			$new_width = floor($width*$scale);
			$new_height = floor($height*$scale);
			
			$tmp_img = imagecreatetruecolor($new_width, $new_height);
			imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			
			imageJpeg($tmp_img, $outFile);
			imagedestroy($tmp_img);
		}
		
		imagedestroy($img);
	}
	else
	{
		copy($image, $outFile);
	}
	
	return $outFile;
}

function query($sql)
{
	debug('Query : '. $sql);
	
	($rh = mysql_query($sql)) or debug('SQL error : '. mysql_error());
	
	return $rh;
}

function selectQuery($sql)
{
	$ret = array();
	
	$rh = query($sql);
	
	while ( $row = mysql_fetch_assoc($rh) )
	
		array_push($ret, $row);
		
	return $ret;
}

function formatText($text)
{
	$text = preg_replace("/\n/", '<br/>', $text);
	
	return $text;
}

function debug($trace)
{
	if ( getConfiguration('debug','debug')=='on' )

		echo '<div class="debug-trace">[trace] '. $trace .'</div>';
}

function initDatabase()
{
	$host = getConfiguration('database', 'Host');
	$username = getConfiguration('database', 'Username');
	$password = getConfiguration('database', 'Password');
	$database = getConfiguration('database', 'Database');
	
	mysql_connect($host,$username,$password) or debug('SQL error : '. mysql_error());
	mysql_select_db($database);
}

function initSession()
{
	if ( ! array_key_exists('user', $_SESSION) && array_key_exists('password', $_COOKIE) )
	{
		$email = $_COOKIE['email'];
		$password = $_COOKIE['password'];
	
		if ( get_magic_quotes_gpc()==0 )
		{
			$email = addslashes($email);
			$password = addslashes($password);
		}
		
		$rh = query("SELECT id FROM user WHERE email='$email' AND PASSWORD(password)='$password';");
		
		if ( mysql_num_rows($rh)==1 )
		{
			list($id) = mysql_fetch_array($rh);
			$_SESSION['user'] = $id;
		
			logEvent(2,'');
		}
		else
			setcookie('password', '', 0, '/');
	}
	
	if ( array_key_exists('user', $_SESSION) )
	{
		$rh = query("SELECT id,email,PASSWORD(password) FROM user WHERE id=${_SESSION[user]};");
		
		if ( mysql_num_rows($rh)==1 )
		{
			list($id,$email,$pass) = mysql_fetch_array($rh);
		
			setcookie('email', $email, time()+60*60*24*600, '/');
			setcookie('password', $pass, time()+60*60*24*600, '/');
		}
		else
		{
			setcookie('password', '', 0, '/');
			
			unset($_SESSION['user']);
		}
	}
}

function param($parameter)
{
	$value='';
	
	if ( array_key_exists($parameter, $_POST) )
		$value = $_POST[$parameter];
		
	elseif ( array_key_exists($parameter, $_GET) )
		$value = $_GET[$parameter];
	
	$value = escape($value);
		
	return trim($value);
}

function escape($value)
{
	if ( get_magic_quotes_gpc()==0 )
		return addslashes($value);
	else
		return $value;
}

$Navigation = array();
$Configuration = loadIniFile('../Configurations.txt');

//if ( $_GET['lang']==getConfiguration('global', 'DefaultLanguage') )

//	redirect( substr( getenv('REQUEST_URI'), 3 ) );

initDatabase();
loadLanguage();
initSession();

?>
